package com.ts.api.http.org.utils;

import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.algorithm.encrypt.asymmetric.RSA;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.reflection.ReflectionUtils;
import com.gitee.apanlh.util.valid.ValidParam;

import java.util.Map;

/**
 *  庆鱼工具类
 *
 *  @author Pan
 */
public class ApiQingYuUtils {

    /**
     *  获取签名
     *
     *  @param  map
     *  @return String
     */
    public static String sign(Map<String, Object> map) {
        StringBuilder sb = new StringBuilder();

        String t10 = String.valueOf(map.get("t10"));

        IteratorUtils.entrySet(map, (key, value) -> {
            if (ValidParam.isNotNull(value)) {
                if (key.equals("t10")) {
                    return ;
                }
                sb.append(key).append(value);
                if (key.equals("t1")) {
                    sb.append("t10").append(t10);
                }
            }
        });
        return MD5.create().digestToHex(sb.toString(), false);
    }

    /**
     *  加密数据并且设置签名
     *
     *  @param obj
     *  @param publicKey
     */
    public static void encryptData(Object obj, String publicKey) {
        Map<String, Object> map = ClassConvertUtils.toLinkedHashMap(obj);
        String sign = sign(map);
        map.put("sign", sign);

        //  加密
       RSA rsa = new RSA(publicKey, null);

        IteratorUtils.entrySet(map, (key, value) -> {
            if (ValidParam.isNotNull(value)) {
                String encryptData = rsa.encryptToBase64Str(ClassConvertUtils.toStr(value));
                map.put(key, encryptData);
            }
        });

        ReflectionUtils.setFields(obj, map);
    }
}
